package com.simen.sample.com.simen.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 消息提示图标
 */
public class WarnView extends ImageView {

    private Drawable warn;
    private Rect padding;
    private Rect cropRect;


    public WarnView(Context context) {
        this(context, null);
    }

    public WarnView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WarnView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, com.simen.warnview.R.styleable.warn);
        try {
            int paddingLeft = typedArray.getDimensionPixelSize(com.simen.warnview.R.styleable.warn_warn_paddingLeft, 0);
            int paddingTop = typedArray.getDimensionPixelSize(com.simen.warnview.R.styleable.warn_warn_paddingTop, 0);
            int paddingRight = typedArray.getDimensionPixelSize(com.simen.warnview.R.styleable.warn_warn_paddingRight, 0);
            int paddingBottom = typedArray.getDimensionPixelSize(com.simen.warnview.R.styleable.warn_warn_paddingBottom, 0);

            padding = new Rect();
            padding.set(paddingLeft, paddingTop, paddingRight, paddingBottom);

            Drawable warn = typedArray.getDrawable(com.simen.warnview.R.styleable.warn_warn_src);
            setWarnImage(warn, padding);
        } finally {
            typedArray.recycle();
        }
    }

    public void setWarnImage(int drawable) {
        setWarnImage(drawable, null);
    }

    public void setWarnImage(int drawable, Rect padding) {
        setWarnImage(getResources().getDrawable(drawable), padding);
    }

    private void setWarnImage(Drawable drawable, Rect padding) {
        this.warn = drawable;
        if (padding == null) {
            padding = new Rect(0, 0, 0, 0);
        }
        this.padding = padding;
        this.cropRect = null;
        invalidate();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (warn != null) {
            if (cropRect == null) {
                this.cropRect = new Rect(getWidth() - warn.getIntrinsicWidth(), 0, getWidth(), warn.getIntrinsicHeight());
            }
            warn.setBounds(getCropRect());
            warn.draw(canvas);
        }
    }

    private Rect getCropRect() {
        if (cropRect == null) {
            if (warn != null) {
                cropRect = new Rect(0, 0, warn.getIntrinsicWidth(), warn.getIntrinsicHeight());
            } else {
                return new Rect(0, 0, 0, 0);
            }
        }
        return cropRect;
    }
}
